/**
 * Created by tanbingqin on 2020/3/10.
 */
import React, { Component, PropTypes } from "react";
import { messages, getQueryUrlParam } from 'share/common'
import { connect } from 'react-redux';
import SlideDocument from 'components/template/slide-document/slide-document'
import requestService from 'containers/request/request.service'
import baseService from 'share/base.service'
import errorMessage from 'share/errorMessage';
import 'styles/request/new-card-request.scss'
import BottomBlock from "./bar/bottom-block";
import requestUtil from 'containers/request/slide/request-util'
import { message, Affix, Tabs } from 'antd'
const TabPane = Tabs.TabPane;
import MentionBtn from 'containers/request/btns/mention-btn'
import RecallBtn from 'containers/request/btns/recall-btn'
import PrintBtn from 'containers/request/btns/print-btn'
import ExpireBtn from 'containers/request/btns/expire-btn'
import RestartBtn from 'containers/request/btns/restart-btn'
import GoErBtn from 'containers/request/btns/go-er-btn'
import TransferBtn from 'containers/request/btns/transfer-btn'
import GoBackBtn from 'containers/request/btns/go-back-btn'
import ApproveRequestBtn from 'containers/approve/request/approve-request-btn'
import TravelUpdateBtn from 'containers/request/btns/travel-update-btn'

import ItineraryBlock from 'containers/request/slide/content/itinerary'
import ApproveHistory from 'components/template/approve-history'
import BudgetExplain from 'components/template/budget-explain/budget-explain'
import Condition from 'components/condition';
const If = Condition.If;
import ApplicationHeader from 'containers/request/slide/content/application-header'
import ApproveTag from 'components/template/approve-tag'
import menuRoute from 'routes/menuRoute'

class RequestDetail extends Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      form: {},
      info: {},
      adminApprove: false, //是否是流程监控平台跳转过来的
      isShowCredit: false, //是否展示信用，读取后台配置，从流程监控，费用查看跳转过来的不受此配置限制
      readOnly: false, //页面在没任何特殊逻辑的情况下的只读
      budgetExplainNumber: 0, //预算执行情况列表数量
      thirdPartyInfo: {}, //第三方返回信息
      creditScore: {}, //信用相关数据
      jobInfo: {}, //岗位信息
      applicant: {}, //申请人信息
      activeTab: 'itinerary', //默认tab
      isCollapsed: false, //是否是展开的
      isHasItinerary: true, //是否有行程数据信息，默认有，渲染子组件，再根据自组件获取的数据来判断是否有行程数据
      quotaObj: {
        takeQuota: false, //是否申请额度
        quotaAmount: 0, //额度金额
        quotaCurrencyCode: 'CNY', //额度币种
        quotaBankCardOID: '' //额度银行卡id
      }, //申请额度相关的字段
      showUserStatus: false, // feature 12962 审批+配配置显示离职信息
    }
  }

  componentDidMount() {
    this.initData();
  }

  //处理页面来源，页面状态，审批，禁用等字段
  initData = () => {
    const { _isSlideFrame, params } = this.props;
    const { admin, entry, status } = this.props.params;
    if (_isSlideFrame) {
      this.setState({
        approving: status === 'approving',
        adminApprove: admin,
        [entry]: entry  //entry: costApplication是否是费用查看列表跳转过来的
      }, this.initReadOnly);
    } else {
      //处理邮件跳转，关联单据跳转到申请单的情况
      this.setState({
        approving: this.props.location.query.approving,
        approve: this.props.location.pathname.indexOf('approve-request-detail') > -1,
        audit: this.props.location.pathname.indexOf('loan-request-detail-audit') > -1,
        view: this.props.location.pathname.indexOf('finance-view') > -1,
        loanRefund: this.props.location.pathname.indexOf('loan-refund-detail') > -1,
        adminApprove: this.props.location.pathname.indexOf('admin-approve-request-detail') > -1,
        costApplication: this.props.location.pathname.indexOf('cost-application-detail') > -1,
      }, this.initReadOnly)
    }
    this.setState({ showUserStatus: this.props.newProfile['approvalControlOpt']['showUserStatus'] === true && entry === 'approve'})
  };

  initReadOnly = () => {
    const { approve, audit, view, loanRefund, adminApprove } = this.state;
    const { _isSlideFrame, params, location } = this.props;
    let readOnlyParam = _isSlideFrame ? params.readOnly : location.query.readOnly;
    this.setState({
      readOnly: adminApprove || approve || audit || view || loanRefund || readOnlyParam,
    });
    this.getInfo();
  };

  //评论成功的回调
  refreshInfo = () => {
    this.getInfo();
  };

  getInfo = () => {
    const { formOID, applicationOID } = this.props.params;
    this.setState({loading: true});
    Promise.all([
      requestService.getFormType(formOID),
      requestService.getRequestDetail(applicationOID),
      requestService.getUserCreditConfig()
    ]).then(res => {
      //将是否是管理员添加进去
      res[1].data.admin = this.state.adminApprove;
      this.setState({
        form: res[0].data,
        info: res[1].data,
        isShowCredit: (res[2] && res[2].data && res[2].data.show) || (this.state.costApplication || this.state.adminApprove) //开启管控 费用查看和流程监控平台不受控制
      }, () => {
        this.getOtherInfo();
        this.initQuotaObj();
      });
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  //初始化申请额度相关信息
  initQuotaObj = () => {
    const { info } = this.state;
    let { quotaObj } = this.state;
    quotaObj.takeQuota = info.takeQuota;
    quotaObj.quotaAmount = info.quotaAmount;
    quotaObj.label = info.quotaBankCardDTO ? `${info.quotaBankCardDTO.paymentRemark === '002' ? messages('request-1.key15')/*瑞贝卡*/ : messages('request-1.key16')/*领创A卡*/}(${info.quotaBankCardDTO.bankAccountNo && info.quotaBankCardDTO.bankAccountNo.substr(-4)})` : '';
    quotaObj.quotaBankCardOID = info.quotaBankCardOID;
    quotaObj.quotaBankCardDTO = info.quotaBankCardDTO;
    this.setState({quotaObj});
  };

  //处理其余信息：岗位，信用，预算调用等等
  getOtherInfo = () => {
    const { info, isShowCredit, readOnly } = this.state;
    Promise.all([
      requestService.getBudgetExplain({
        applicationOID: info.applicationOID,
        mark: !!readOnly
      }),
      isShowCredit && requestService.getUserCredit(info.applicant.userOID, info.jobId),
      baseService.getJobInfo(info.jobId),
      baseService.getUserInfo(info.applicantOID)
    ]).then(res => {
      this.setState({
        loading: false,
        budgetExplainNumber: Number(res[0].data || 0),
        creditScore: res[1] ? res[1].data || {} : {},
        jobInfo: res[2].data || {},
        applicant: res[3].data
      }, this.getThirdPartyInfo);
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });

    if (this.state.approve) {
      let info = this.state.info;
      this.setState({showApproveBottom: requestUtil.showApproveButton(info.approvalChain, info.approvalChains, this.props.user.userOID, info.status)});
    }
    this.isShowChangedStatus(); //待审批详情是否单据状态已变更
  };

  //处理第三方返回信息
  getThirdPartyInfo = () => {
    const { info } = this.state;
    const { profile } = this.props;
    if (profile['request.external.info.display']) {
      requestService.getThirdPartyInfo(info.applicationOID).then(res => {
        this.setState({thirdPartyInfo: res.data});
      }).catch(err => {
        errorMessage(err.response);
      });
    }
  };

  //员工待审批详情页进来的，但是单据状态不是审批中，需要弹提示语
  isShowChangedStatus = () => {
    const { approve, info, approving } = this.state;
    if (approving && approve && info.status !== 1002) {
      message.info(messages('request-1.key1')/*无须审批，单据可能已被他人处理*/);
    }
  };

  handleCollapse = (value) => {
    this.setState({isCollapsed: value});
  };

  getChildContext() {
    const { form, info, creditScore, jobInfo, applicant, thirdPartyInfo, showUserStatus } = this.state;
    return {
      applicant,
      creditScore,
      form,
      info,
      jobInfo,
      close: () => this.goBack(),
      refreshInfo: () => this.refreshInfo(),
      thirdPartyInfo,
      showUserStatus
    }
  }

  goBack = (isNeedRefreshList) => {
    const { _isSlideFrame, close } = this.props;
    const { isPreVersion } = _isSlideFrame ? this.props.params : this.props.location.query;
    const { backType, pageFrom, tab } = this.props.params;
    if (isPreVersion) {
      this.context.router.push(menuRoute.getRouteItem('request').url);
      return;
    }
    if (backType === 'history') {
      window.history.go(-1);
    } else {
      if (close) {
        close(isNeedRefreshList);
      } else {
        //老逻辑的页面跳转只有my和closeList两种情况
        pageFrom && pageFrom === 'my' && this.context.router.push(menuRoute.getRouteItem('expense-report').url);
        pageFrom && pageFrom === 'closeList' && this.context.router.push(menuRoute.getRouteItem('request-close').url);
        //老逻辑且没有pageFrom，则跳到申请单列表，ps：流程监控平台没用这个goBack方法，是另外处理的
        !pageFrom && this.context.router.push(menuRoute.getRouteItem('request').url);
      }
    }
  };

  renderBottom = () => {
    const { info, form: formInfo } = this.state;
    const { readOnly, approve, loanRefund, view, adminApprove, approving, showApproveBottom, costApplication, audit } = this.state;
    const { entry, approverOID, approvalMode } = this.props.params;
    const { _isSlideFrame } = this.props;
    const { from, readOnly: readOnlyFromUrl } = _isSlideFrame ? this.props.params : this.props.location.query;
    let formType = formInfo.formType;
    let bottomBar = "bottom-bar";
    if (!readOnly || approve || loanRefund || view || adminApprove) {
      return (
        <Affix offsetBottom={0} className={`bottom-bar ${((approve && approving && showApproveBottom) || (!approve && approving)) ? 'bottom-bar-approve' : ''}`}>
          {!readOnly && <MentionBtn info={info} customFormPropertyMap={formInfo.customFormPropertyMap} goBack={this.refreshInfo} />}
          {!readOnly && <RecallBtn info={info} recallEnable={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['formWithdrawAuthority']} goBack={this.goBack}/>}
          {(!readOnly || view) && <PrintBtn info={info} printFlag={view}/>}
          {!readOnly && <ExpireBtn formType={Number(formType)} info={info} goBack={this.goBack}/>}
          {!readOnly && <RestartBtn formType={Number(formType)} info={info} goBack={this.goBack}/>}
          {!readOnly && <GoErBtn info={info}/>}
          {!readOnly && entry !== 'closeList' && (
            <TravelUpdateBtn
              formType={Number(formType)}
              info={info}
              updateEnable={formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['application.change.enable']}
            />
          )}
          {!readOnly && entry !== 'closeList' && (
            <TransferBtn formType={Number(formType)} info={info} goBack={this.goBack}/>
          )}
          {!readOnly && (from !== 'expense' && from !== 'request') &&  //从报销单／申请单进来的关联申请单，因为是新开tab，不需要返回按钮
            <GoBackBtn goBack={this.goBack}/>
          }
          {approve && !adminApprove && !readOnlyFromUrl &&
            <ApproveRequestBtn
              formType={Number(formType)}
              info={info}
              approving={!!approving && showApproveBottom}
              approverOID={approverOID || getQueryUrlParam('approverOID')}
              formInfo={formInfo}
              goBack={this.goBack}
              handleApproveMention={this.refreshInfo}
            />
          }
          {adminApprove && !readOnlyFromUrl &&
            <ApproveRequestBtn
              formType={Number(formType)}
              info={info} //管理员审批
              approving={!!approving}
              formInfo={formInfo}
              goBack={this.goBack}
              approvalMode={approvalMode || getQueryUrlParam('approvalMode')}
              approverOID={approverOID || getQueryUrlParam('approverOID')}
            />
          }
        </Affix>
      )
    }
    if (readOnly && !costApplication && !approve && !adminApprove && !loanRefund && !view && !audit && entry !== 'financeView') {
      return (
        <Affix offsetBottom={0} className={bottomBar}>
          <GoBackBtn goBack={this.goBack}/>
        </Affix>
      )
    }
    if (readOnly && costApplication) {
      return (
        <Affix offsetBottom={0} className={bottomBar}>
          <PrintBtn info={info} printFlag={costApplication}/>
          <GoBackBtn goBack={this.goBack}/>
        </Affix>
      )
    }
    if (entry === 'financeView' && info.printButtonDisplay) {
      return (
        <Affix offsetBottom={0} className={bottomBar}>
          <PrintBtn info={info} />
        </Affix>
      )
    }
    return null;
  };

  judgeItinerary = (itineraryList) => {
    this.setState({isHasItinerary: !!itineraryList.length});
    if (!itineraryList.length) {
      this.setState({activeTab: 'approvals'});
    }
  };

  render() {
    const { entry, approverOID } = this.props.params;
    const { _isSlideFrame } = this.props;
    const { readOnly: readOnlyFromUrl, isPreVersion } = _isSlideFrame ? this.props.params : this.props.location.query;
    const { loading, info, activeTab, budgetExplainNumber, isCollapsed, approving, costApplication, showApproveBottom,
      adminApprove, isHasItinerary, quotaObj, readOnly } = this.state;
    return (
      <SlideDocument
        loading={loading}
        className='slide-request-detail'
        onClickCollapse={this.handleCollapse}
        fieldsParams={{
          annotateDisabled: true,
          showEdit: false //审批中编辑在application-header里处理
        }}
        left={
          <div className="slide-application-header">
            <If value={info.applicationOID}>
              <ApplicationHeader
                isCheckEdit={!!approving && !readOnlyFromUrl}
                approverOID={approverOID}
                costApplication={!!costApplication}
                quotaObj={quotaObj}
                isPreVersion={isPreVersion}
              />
            </If>
          </div>
        }
        right={
          <div className='slide-request-detail-right'>
            <If value={info.applicationOID}>
              <Tabs
                activeKey={activeTab}
                className="right-tabs"
                onChange={activeTab => this.setState({ activeTab })}
              >
                {isHasItinerary && (
                  <TabPane tab={messages('request-1.key271')/*行程明细*/} key='itinerary'>
                    <ItineraryBlock disabled isCollapsed={isCollapsed} refreshItinerary={this.judgeItinerary} isReadOnly={readOnly} />
                  </TabPane>
                )}
                {budgetExplainNumber > 0 && (
                  <TabPane tab={messages('request-1.key23')/*预算执行信息*/} key="budgetExplain">
                    <div className="budget-explain-block">
                      <BudgetExplain documentType="EXP_REQUISITION" documentId={info.applicationOID}/>
                    </div>
                  </TabPane>
                )}
                {info.approvalHistorys && info.approvalHistorys.length && (
                  <TabPane tab={messages('request-1.key24')/*审批历史*/} key="approvals">
                    <ApproveHistory
                      approvalChains={info.approvalChains}
                      isShowReply={entry === 'my' && info.status === 1003}
                      businessCode={info.businessCode}
                      approvalHistory={info.approvalHistorys}
                      applicantInfo={info.applicant || {}}
                    />
                  </TabPane>
                )}
              </Tabs>
            </If>
            {!!approving && !readOnlyFromUrl && (showApproveBottom || adminApprove) && info.applicationOID && (
              <ApproveTag entityOID={info.applicationOID} approverOID={approverOID}/>
            )}
          </div>
        }
        bar={this.renderBottom()}
      />
    )
  }
}

RequestDetail.childContextTypes = {
  applicant: PropTypes.object,
  creditScore: PropTypes.object,
  jobInfo: PropTypes.object,
  form: PropTypes.object,
  info: PropTypes.object,
  close: PropTypes.func,
  refreshInfo: PropTypes.func,
  thirdPartyInfo: PropTypes.object,
  showUserStatus: PropTypes.bool
};

RequestDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    newProfile: state.login.options
  }
}

export default connect(mapStateToProps)(RequestDetail)
